package com.xiang._02.strategy;

import java.util.Arrays;

public enum SaveStrategyEnum {

    DB("db") {
        @Override
        public void save(Object obj) {
            System.out.println("save in db:" + obj);
        }
    },
    FILE("file") {
        @Override
        public void save(Object obj) {
            System.out.println("save in file: " + obj);
        }
    },
    OSS("oss") {
        @Override
        public void save(Object obj) {
            System.out.println("save in oss: " + obj);
        }
    };
    private String type;
    SaveStrategyEnum(String type) {
        this.type = type;
    }

    public abstract void save(Object obj);


    public static SaveStrategyEnum typeOf(String type) {
//        for (SaveStrategyEnum strategyEnum: values()) {
//            if (strategyEnum.type.equalsIgnoreCase(type)) {
//                return strategyEnum;
//            }
//        }
//        return null;

        // java8 高级一点
        return Arrays.stream(SaveStrategyEnum.values())
                .filter(c -> c.type.equalsIgnoreCase(type)).findFirst()
                .orElse(null);


    }

    public void save(String type, Object data) {
        SaveStrategyEnum strategyEnum = SaveStrategyEnum.typeOf(type);
        if (strategyEnum != null) {
            strategyEnum.save(data);
        }
    }


}
